<template>
  <div class="weather-container">
    <div class="wrap content">
      <div class="citySearch">
        <input
          type="text"
          placeholder="请输入城市名称"
          v-model.trim="cityName"
          @input="handleSearchCityTest"
        />
      </div>
      <ul class="search-result" v-if="cityName">
        <li
          v-if="status === '1'"
          v-for="item in choices"
          :key="item.adcode"
          @click="handleSearchCity"
        >
          {{ item.city }}
        </li>
        <p v-else>{{ messageShow }}</p>
      </ul>
      <div class="citySearch-List" v-else-if="cityWeatherList.length">
        <div
          class="list-item"
          v-for="item in cityWeatherList"
          :key="item.Adcode"
        >
          <CityItem :item="item" />
        </div>
      </div>
      <div class="no-data" v-else>
        <h1>暂时没有保存过城市天气信息,请查询后点击右上角"+"号保存</h1>
      </div>
      <Charts :weatherInFourDays="cityWeatherInFourDaysHome" />
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { WeatherStore } from '@/stores/counter.js';
import { storeToRefs } from 'pinia';
import { useRouter } from 'vue-router';
import {
  getCityByIP,
  getAdcodeByCity,
  getAllWeatherByAdcode,
} from '@/api/index.js';

import CityItem from '@/components/CityItem.vue';
import Charts from '@/components/Charts.vue';

const router = useRouter();
const cityName = ref('');
const cityWeatherInFourDaysHome = ref([]);
const status = ref('');
const infocode = ref('');
const choices = ref([]);
const weatherStore = WeatherStore();
const { cityWeatherList } = storeToRefs(weatherStore);
const { getCityWeatherList } = weatherStore;

// 计算属性，显示提示信息
const messageShow = computed(() => {
  return status.value === '0' &&
    (infocode.value === '20000' || infocode.value === '30001')
    ? '网络问题，请稍后再试'
    : '未找到匹配的城市';
});

// 简单的防抖函数实现
const debounce = (func, wait) => {
  let timeout;
  return function executedFunction(...args) {
    const later = () => {
      clearTimeout(timeout);
      func(...args);
    };
    clearTimeout(timeout);
    timeout = setTimeout(later, wait);
  };
};

// 设置了防抖函数，防止用户输入过快导致请求过多
const handleSearchCityTest = debounce(async () => {
  choices.value = [];
  status.value = '';
  infocode.value = '';
  const reg = /[\u4e00-\u9fa5]/;
    if (cityName.value.trim().length >= 1 && reg.test(cityName.value.trim())) {
    const res = await getAdcodeByCity(cityName.value);
    status.value = res.status;
    infocode.value = res.infocode;
    choices.value = res.geocodes;
  } else {
    return;
  }
}, 100);

// 点击搜索按钮，跳转到城市天气页面
const handleSearchCity = async (event) => {
  const res = await getAdcodeByCity(cityName.value);
  router.push({
    name: 'cityweather',
    params: { Adcode: res.geocodes[0].adcode },
    query: { search: event.target.textContent },
  });
};

// 页面加载完成后，获取当前用户IP所在城市的天气信息
onMounted(async () => {
  getCityWeatherList();
  const res = await getCityByIP();
  const res2 = await getAllWeatherByAdcode(res.adcode);
  cityWeatherInFourDaysHome.value = res2.forecasts[0].casts;
});
</script>

<style lang="scss" scoped>
.weather-container {
  min-height: 100vh;
  color: #fff;
  background-color: #00668a;
  .content {
    .citySearch {
      input {
        margin-top: 20px;
        width: 100%;
        height: 30px;
        font-size: 16px;
        color: #fff;
        background-color: transparent;
        border: none;
        border-bottom: 1px solid #fff;
        &:focus {
          outline: 2px solid transparent;
          outline-offset: 2px;
          border: none;
          // 聚焦时，输入框的阴影
          box-shadow: 0 3px 4px #06526d;
        }
        // 设置输入框placeholder颜色
        &::placeholder {
          color: #8793a7;
        }
      }
    }
    .search-result {
      width: 100%;
      font-size: 18px;
      color: #fff;
      // 设置搜索结果列表为透明
      background-color: transparent;
      p {
        margin-top: 10px;
      }
      li {
        height: 40px;
        line-height: 40px;
        background-color: #004e71;
        margin-top: 5px;
        padding-inline: 10px;
        cursor: pointer;
      }
    }
    .citySearch-List {
      margin-top: 50px;
    }
    .no-data {
      margin: 50px auto;
      h1 {
        font-size: 18px;
        color: #fff;
        text-align: center;
      }
    }
  }
}
</style>